package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"net/url"
	"oauth_test/model"
)

var link string = model.AuthGet.Url + "?client_id=" + model.AuthGet.ClientId +
	"&redirect_uri=" + model.AuthGet.RedirectUrl + "&response_type=code"

func main() {
	r := gin.Default()
	fmt.Println(link)
	r.GET("/v1/login", func(c *gin.Context) {
		link = link + "&scope=user_info"
		fmt.Println(link)
		c.Redirect(301, link)
	})

	r.GET("/v1/oauth/callback", func(c *gin.Context) {
		code := c.Query("code")
		getaccess := fmt.Sprintf("https://gitee.com/oauth/token?grant_type=authorization_code&code=%s&client_id=%s&redirect_uri=%s&scope=user_info",
			code,
			model.AuthGet.ClientId,
			model.AuthGet.RedirectUrl,
		)

		resp, err := http.PostForm(getaccess, url.Values{
			"client_secret": {model.AuthGet.ClientSecret},
		})
		if err != nil {
			fmt.Println("http.PostForm")
			return
		}
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			fmt.Println(err)
			return
		}
		c.Writer.Write(body)
		fmt.Println(string(body))
	})

	r.GET("v1/oauth/token", func(c *gin.Context) {
		body, err := ioutil.ReadAll(c.Request.Body)
		if err != nil {
			fmt.Println(err)
			return
		}
		c.Writer.Write(body)
		fmt.Println(string(body))
	})

	r.Run(":8081")
}
